package com.qianniu.napi.common.util;

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.URL;

public class EhcacheUtil {

    private static final Logger logger = LoggerFactory.getLogger(EhcacheUtil.class);

    private static final String path = "/ehcache.xml";

    private URL url;

    private CacheManager manager;

    private static EhcacheUtil ehCache;

    private EhcacheUtil(String path) {
        url = getClass().getResource(path);
//        manager = CacheManager.create(url);
        manager = CacheManager.create();
//        if (manager != null) logger.debug("========EhcacheUtil manager=" + manager);
//        else logger.debug("========EhcacheUtil manager is null");
//        String[] caches = manager.getCacheNames();
//        for (String item : caches) {
//            logger.debug("========EhcacheUtil item =" + item);
//        }
    }

    public static EhcacheUtil getInstance() {
        if (ehCache == null) {
            ehCache = new EhcacheUtil(path);
        }
        return ehCache;
    }

    public void put(String cacheName, String key, Object value) {
        Cache cache = manager.getCache(cacheName);
        Element element = new Element(key, value);
        cache.put(element);

    }

    public Object get(String cacheName, String key) {
        Cache cache = manager.getCache(cacheName);
        Element element = cache.get(key);
        return element == null ? null : element.getObjectValue();
    }

    public Cache get(String cacheName) {
        return manager.getCache(cacheName);
    }

    public void remove(String cacheName, String key) {
        Cache cache = manager.getCache(cacheName);
        cache.remove(key);
    }

//    /**
//     * 设置缓存对象
//     * @param cacheManager
//     * @param key
//     * @param object
//     */
//    public static void setCache(CacheManager cacheManager, String key, Object object){
//        Cache cache = cacheManager.getCache("objectCache");
//        Element element = new Element(key,object);
//        cache.put(element);
//    }
//    /**
//     * 从缓存中取出对象
//     * @param cacheManager
//     * @param key
//     * @return
//     */
//    public static Object getCache(CacheManager cacheManager,String key){
//        Object object = null;
//        Cache cache = cacheManager.getCache("objectCache");
//        if(cache.get(key)!=null && !cache.get(key).equals("")){
//            object = cache.get(key).getObjectValue();
//        }
//        return object;
//    }

}
